﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using IF.Utils;
using System.IO;
using Newtonsoft.Json.Linq;

namespace IFStudio
{
    public partial class OrderImplrt : Form
    {
        public OrderImplrt()
        {
            InitializeComponent();
        }
        //路径
        private string path;
        public string GetOrderPushDataParam(DataRow dtro, BackgroundWorker param_bgw_Process)
        {
            Dictionary<string, object> dicReq = new Dictionary<string, object>();
            if (string.IsNullOrEmpty(dtro["订单号"].ToString()))
            {
                return "";
            }
            dicReq.Add("tid", dtro["订单号"].ToString());//平台订单编号s
            dicReq.Add("trade_status", "30");//30已付款待发货
            dicReq.Add("pay_status", "2");//付款状态:0未付款1部分付款2已付款
            dicReq.Add("delivery_term", 4);//发货条件:1款到发货 2货到付款(包含部分货到付款)
            dicReq.Add("trade_time", Convert.ToDateTime(dtro["购买时间"].ToString()));//推送时间
            dicReq.Add("pay_time", "");//支付时间
            dicReq.Add("buyer_nick", "美团网");//网名
            dicReq.Add("buyer_email", "");//..
            dicReq.Add("pay_id", "");
            dicReq.Add("pay_account", "");//省份	城市	区
            dicReq.Add("receiver_name", dtro["收件人"].ToString());
            dicReq.Add("receiver_province", dtro["省份"].ToString());
            dicReq.Add("receiver_city", dtro["城市"].ToString());
            dicReq.Add("receiver_district", dtro["区"].ToString());
            dicReq.Add("receiver_address", dtro["详细地址"].ToString());
            dicReq.Add("receiver_mobile", dtro["联系电话"].ToString());
            dicReq.Add("receiver_telno", "");
            dicReq.Add("receiver_zip", dtro["邮编"].ToString());
            dicReq.Add("logistics_type", "ZTO");
            dicReq.Add("invoice_type", 0);
            dicReq.Add("invoice_title", "");
            dicReq.Add("buyer_message", "");
            dicReq.Add("seller_memo", "");
            dicReq.Add("seller_flag", "0");
            dicReq.Add("post_amount", 0);
            dicReq.Add("cod_amount", "0");
            dicReq.Add("ext_cod_fee", "0");
            dicReq.Add("paid", 0);

            List<object> detailList = new List<object>();

            var datail = new
            {
                oid = DateTime.Now.ToFileTime().ToString(),
                num = dtro["购买数量"].ToString(),
                price = dtro["标价"].ToString(),
                status = 30,
                refund_status = 0,
                goods_id = "",
                spec_id = "",
                goods_no = dtro["货品编码"].ToString(),// item.GoodNo,
                spec_no = dtro["规格编码"].ToString(),// item.MerchantNo,//.Remove(0, item.GoodNo.Length),
                goods_name = "",
                spec_name = "",
                adjust_amount = 0,
                discount = Convert.ToDecimal(Convert.ToDecimal(dtro["优惠"].ToString()) * Convert.ToInt32(dtro["购买数量"].ToString())),
                share_discount = 0,
                cid = ""

            };
            param_bgw_Process.ReportProgress(1, dtro["订单号"].ToString() + "---- 订单数据加载完成\r");

            detailList.Add(datail);
            dicReq.Add("order_list", detailList);

            List<object> list = new List<object>();
            list.Add(dicReq);

            //转成JSon
            string json = JsonConvert.SerializeObject(list);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("sid", WDTUtil.SID);
            dic.Add("appkey", WDTUtil.APPKEY);
            dic.Add("timestamp", WDTUtil.DateTimeToStamp(DateTime.Now).ToString());
            dic.Add("shop_no", WDTUtil.SHOPNO);
            dic.Add("trade_list", json);
            param_bgw_Process.ReportProgress(1, dtro["订单号"].ToString() + "---- 订单数据JSON转换完成\r");
            string resutl = WDTUtil.SendPost("/openapi2/trade_push.php", dic);
            //解析 json
            JObject obj_ProductJson = JObject.Parse(resutl);
            //状态成功
            int resultCode = Convert.ToInt32(obj_ProductJson["code"].ToString());
            //新增数量
            int orderCount = Convert.ToInt32(obj_ProductJson["new_count"].ToString());
            if (resultCode == 0 && orderCount > 0)
            {
                param_bgw_Process.ReportProgress(1, dtro["订单号"].ToString() + "---- 订单推送成功\r");
            }
            else
            {
                param_bgw_Process.ReportProgress(1, dtro["订单号"].ToString() + "---- 订单推送失败\r");
            }
            param_bgw_Process.ReportProgress(1, "↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑\r");
            //return string.Format("{1}/trade_push.php?{0}", CreateParam(dic,true), TransConstConfig.ErpUrl);
            return resutl;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(path) && string.IsNullOrEmpty(this.txt_Path.Text))
            {
                return;
            }
            if (string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(this.txt_Path.Text))
            {
                path = this.txt_Path.Text.Trim();
            }
            this.bgw_Process.RunWorkerAsync();
        }

        private void OrderImplrt_DragEnter(object sender, DragEventArgs e)
        {
            this.path = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            this.txt_Path.Text = this.path;
            //this.txt_Info.Text = "准备！！！";
        }

        private void bgw_Process_DoWork(object sender, DoWorkEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            DataTable DT = NOPIHelper.RenderDataTableFromExcel(path, "Table1", 0);
            foreach (DataRow item in DT.Rows)
            {
                sb.Append(GetOrderPushDataParam(item, this.bgw_Process) + "\r\n");
            }
            e.Result = "----------处理完成----------\r\n";
        }

        private void bgw_Process_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.txt_ShowInfo.AppendText(e.UserState.ToString() + "\r\n");
        }

        private void bgw_Process_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.txt_ShowInfo.AppendText(e.Result.ToString());
        }

        private void btn_CancelOrder_Click(object sender, EventArgs e)
        {
            MaoyanUtil.CancelOrderPushDataParam();
        }
    }
}
